<script>
// #ifdef APP-PLUS
import APPUpdate from '@/uni_modules/zhouWei-APPUpdate/js_sdk/appUpdate'
// #endif

export default {
  globalData: {
    pre_url: '',
    baseurl: '',
    session_id: '',
    gtktoken: '',
    aid: 0,
    mid: 0,
    pid: 0,
    needAuth: 0,
    platform: 'wx',
    platform2: '',
    isdouyin: 0,
    sysset: [],
    indexurl: '/pages/index/index',
    menudata: [],
    menu2data: [],
    currentIndex: -1,
    initdata: {},
    textset: [],
    isinit: false,
    socketOpen: false,
    socket_token: '',
    socketMsgQueue: [],
    socketConnecttimes: 0,
    socketInterval: null,
    scene: 0,
    homeNavigationCustom: 0,
    usercenterNavigationCustom: 0,
    navigationBarBackgroundColor: '#ffffff',
    navigationBarTextStyle: 'black',
    rewardedVideoAd: {},
    token: '',
    urlaid: 0,
    paraString: ''
  },
  onLaunch: function (options) {
    // #ifdef APP-PLUS
    APPUpdate()

    plus.globalEvent.addEventListener('newintent', e => {
      this.checkArguments()
    })
    // #endif

    var extConfig = uni.getExtConfigSync ? uni.getExtConfigSync() : {}
    if (extConfig && extConfig.aid) {
      this.globalData.aid = extConfig.aid
      // this.globalData.pre_url = extConfig.baseurl;
      this.globalData.homeNavigationCustom = extConfig.homeNavigationCustom || 0
      this.globalData.usercenterNavigationCustom = extConfig.usercenterNavigationCustom || 0
      this.globalData.navigationBarBackgroundColor = extConfig.navigationBarBackgroundColor || '#ffffff'
      this.globalData.navigationBarTextStyle = extConfig.navigationBarTextStyle || 'black'
    } else {
      var siteInfo = require('./siteinfo.js')
      this.globalData.aid = siteInfo.uniacid
      // #ifdef H5
      var url = window.location.href.split('#')[0]
      var urlArr = url.split('/')
      var htmlname = urlArr[urlArr.length - 1]
      var uniacid = htmlname.replace('.html', '')
      //获取当前页面
      if (uniacid == 'index' || uniacid == undefined || uniacid.length == 0) {
        this.paraString = window.location.href //还可以  window.location.search.substring()
        uniacid = this.getQueryVariable('aid') //code是url后面带的
      }
      console.log(uniacid)
      var reg = /^[0-9]+$/
      if (uniacid && reg.test(uniacid)) {
        this.globalData.aid = uniacid
      }

      // #endif
      this.globalData.pre_url = siteInfo.siteroot

      this.globalData.homeNavigationCustom = siteInfo.homeNavigationCustom || 0
      this.globalData.usercenterNavigationCustom = siteInfo.usercenterNavigationCustom || 0
      this.globalData.navigationBarBackgroundColor = siteInfo.navigationBarBackgroundColor || '#ffffff'
      this.globalData.navigationBarTextStyle = siteInfo.navigationBarTextStyle || 'black'
    }
    this.globalData.baseurl = this.globalData.pre_url + '/'
    this.globalData.session_id = uni.getStorageSync('session_id')
    this.globalData.gtktoken = uni.getStorageSync('gtktoken') || ''
    var opts = this.getopts(options.query)
    if (opts && opts.pid) {
      this.globalData.pid = opts.pid
      uni.setStorageSync('pid', this.globalData.pid)
    } else {
      //var pid = uni.getStorageSync('pid');
      //if (pid) this.globalData.pid = pid;
    }
    if (opts && opts.uid) {
      this.globalData.uid = opts.uid
    }
    if (opts && opts.token != undefined) {
      console.log(opts)
      this.token = opts.token
      //this.setlogin();
    }
    // #ifdef APP-PLUS
    this.globalData.platform = 'app'
    var app = this
    uni.getSystemInfo({
      success: function (res) {
        app.globalData.platform2 = res.platform
      }
    })
    // #endif
    // #ifdef H5
    this.globalData.platform = 'h5'
    if (navigator.userAgent.indexOf('MicroMessenger') > -1) {
      this.globalData.platform = 'mp'
    }
    // #endif
    // #ifdef MP-WEIXIN
    this.globalData.platform = 'wx'
    this.checkUpdateVersion()
    // #endif
    // #ifdef MP-ALIPAY
    this.globalData.platform = 'alipay'
    // #endif
    // #ifdef MP-BAIDU
    this.globalData.platform = 'baidu'
    // #endif
    // #ifdef MP-TOUTIAO
    this.globalData.platform = 'toutiao'
    var sysinfo = tt.getSystemInfoSync()
    if (sysinfo.appName == 'Douyin') {
      this.globalData.isdouyin = 1
    }
    // #endif
    // #ifdef MP-QQ
    this.globalData.platform = 'qq'
    // #endif
    console.log(this.globalData.platform)

    //#ifndef MP-TOUTIAO
    var app = this
    uni.onSocketOpen(function (res) {
      app.globalData.socketOpen = true
      for (var i = 0; i < app.globalData.socketMsgQueue.length; i++) {
        app.sendSocketMessage(app.globalData.socketMsgQueue[i])
      }
      app.globalData.socketMsgQueue = []
    })
    uni.onSocketMessage(function (res) {
      console.log('收到服务器内容：' + res.data)
      try {
        var data = JSON.parse(res.data)
        var needpopup = true
        var pages = getCurrentPages()
        var currentPage = pages[pages.length - 1]
        if (!currentPage) return
        if (currentPage && currentPage.$vm.hasOwnProperty('receiveMessage')) {
          var rs = currentPage.$vm.receiveMessage(data)
          needpopup = !rs
        }
        if (needpopup && (data.type == 'tokefu' || data.type == 'tokehu' || data.type == 'peisong' || data.type == 'notice')) {
          //需要弹窗提示
          currentPage.$vm.$refs.popmsg.open(data)
        }
      } catch (e) {}
    })
    //#endif
  },
  onShow: function (options) {
    var that = this
    console.log('onShow')
    console.log(options)
    console.log('---------xxxx')
    if (options && options.scene) {
      this.globalData.scene = options.scene
    }
    // #ifdef MP-WEIXIN
    // 分享卡片/订阅消息/扫码二维码/广告/朋友圈等场景才能调用getShareParams接口获取以下参数
    const sceneList = [1007, 1008, 1014, 1044, 1045, 1046, 1047, 1048, 1049, 1073, 1154, 1155]
    if (sceneList.includes(this.globalData.scene)) {
      console.log('---------00')
      try {
        let livePlayer = requirePlugin('live-player-plugin')
        console.log(livePlayer)
        console.log('---------11')
        livePlayer
          .getShareParams()
          .then(res => {
            let custom_params = res.custom_params
            console.log(custom_params)
            if (custom_params && custom_params.pid) {
              that.globalData.pid = custom_params.pid
            }
          })
          .catch(err => {
            console.log('get share params err ', err)
          })
      } catch (e) {
        console.log('live-player-plugin err ', e)
      }
    }
    // #endif

    //#ifndef MP-TOUTIAO
    if (that.globalData.mid && that.globalData.socket_token) {
      var app = this
      app.openSocket()
      /*
				app.sendSocketMessage({type: 'khinit',data: {aid: app.globalData.aid,mid: app.globalData.mid,platform:app.globalData.platform} });
				clearInterval(app.globalData.socketInterval);
				app.globalData.socketInterval = setInterval(function () {
					app.sendSocketMessage({type: 'connect'});
				}, 25000);
				*/
    }
    //#endif
  },
  methods: {
    getQueryVariable: function (variable) {
      var query = this.paraString
      var rooms = query.split('?')
      for (var i = 0; i < rooms.length; i++) {
        var pair = rooms[i].split('=')
        if (pair[0] == variable) {
          return pair[1].split('&')[0]
        }
      }
      //或者拼接&后面的值
      var vars = query.split('&')
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=')
        if (pair[0] == variable) {
          return pair[1]
        }
      }
    },
    setlogin: function () {
      var that = this
      this.post('ApiIndex/logintogether', { gtksession: that.token }, function (res) {
        // if (res.status == 1) {
        // 	that.success(res.msg);
        // }else {
        // 	that.error(res.msg);
        // }
      })
    },
    isPhone: function (param) {
      var regExp = new RegExp('^1[35789]\\d{9}$')
      return regExp.test(param)
    },
    isIdCard: function (param) {
      var regExp = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
      return regExp.test(param)
    },
    getopts: function (opt) {
      if (opt && opt.scene) {
        var scene = opt.scene
        var scenes = scene.split('-')
        var opts = {}
        for (var i in scenes) {
          var thisscenes = scenes[i].split('_')
          opts[thisscenes[0]] = thisscenes[1]
        }
        return opts
      } else {
        return opt
      }
    },
    alert: function (content, confirmfun) {
      uni.showModal({
        title: '提示信息',
        showCancel: false,
        content: content.toString(),
        success: function (res) {
          if (res.confirm) {
            typeof confirmfun == 'function' && confirmfun()
          }
        }
      })
    },
    confirm: function (content, confirmfun, cancelfun) {
      uni.showModal({
        title: '操作确认',
        content: content.toString(),
        showCancel: true,
        success: function (res) {
          if (res.confirm) {
            typeof confirmfun == 'function' && confirmfun()
          } else {
            typeof cancelfun == 'function' && cancelfun()
          }
        }
      })
    },
    success: function (title, successfun) {
      if (undefined == title) title = '操作成功'
      var title = title.toString()
      uni.showToast({
        title: title,
        icon: title.length > 8 ? 'none' : 'success',
        success: function (res) {
          typeof successfun == 'function' && successfun()
        }
      })
    },
    error: function (title, duration) {
      if (title === false) {
        uni.hideToast()
      } else {
        if (this.isNull(duration)) duration = 2500
        if (undefined == title) title = '操作失败'
        uni.showToast({
          title: title.toString(),
          icon: 'none',
          duration: duration
        })
      }
    },
    showLoading: function (title) {
      if (title === false) {
        uni.hideLoading()
      } else {
        if (undefined == title) title = '加载中'
        uni.showLoading({
          title: title.toString(),
          mask: true
        })
      }
    },
    inArray: function (search, array) {
      for (var i in array) {
        if (array[i] == search) {
          return true
        }
      }
      return false
    },
    isNull: function (e) {
      return e == undefined || e == 'undefined' || e == null || e == ''
    },
    parseJSON: function (e) {
      try {
        return JSON.parse(e)
      } catch (t) {
        return undefined
      }
    },
    getparams: function (url) {
      if (url.indexOf('?') === -1) return {}
      var query = url.split('?')[1]
      var vars = query.split('&')
      var params = {}
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=')
        params[pair[0]] = pair[1]
      }
      return params
    },
    goto: function (tourl, opentype) {
      var app = this
      var params = app.getparams(tourl)
      console.log(params)
      if (params && params.reloadthispage == 1) {
        var thispage = getCurrentPages().pop()
        thispage.$vm.opt = params
        thispage.$vm.getdata()
        return
      }
      if (app.isNull(opentype) && tourl) {
        //var currentIndex = -1;
        var tablist = app.globalData.menudata['list']
        if (tablist) {
          for (var i = 0; i < tablist.length; i++) {
            if (tablist[i]['pagePath'] == tourl) {
              opentype = 'reLaunch'
            }
          }
        }
      }
      if (tourl.indexOf('pages/') === 0) tourl = '/' + tourl
      if (tourl.indexOf('/pages/commission/') === 0) tourl = tourl.replace('/pages/commission/', '/activity/commission/')
      if (tourl.indexOf('/pages/sign/') === 0) tourl = tourl.replace('/pages/sign/', '/pagesExt/sign/')
      if (tourl.indexOf('/pages/business/') === 0) tourl = tourl.replace('/pages/business/', '/pagesExt/business/')
      if (tourl.indexOf('/pages/lipin/') === 0) tourl = tourl.replace('/pages/lipin/', '/pagesExt/lipin/')
      if (tourl.indexOf('/pages/order/') === 0) tourl = tourl.replace('/pages/order/', '/pagesExt/order/')
      if (app.globalData.isdouyin == 1 && tourl.indexOf('/pages/shop/product') === 0) {
        app.showLoading('加载中')
        app.post(
          'ApiShop/getDouyinProductId',
          {
            proid: params.id
          },
          function (res) {
            app.showLoading(false)
            if (res.status == 1) {
              tt.openEcGood({
                promotionId: res.douyin_product_id,
                fail: function (res2) {
                  app.alert(res2.errMsg)
                }
              })
            } else {
              app.alert(res.msg)
            }
          }
        )
        return
      }
      if (app.globalData.platform == 'wx' && tourl.indexOf('https://work.weixin.qq.com/kfid/') === 0) {
        wx.openCustomerServiceChat({
          extInfo: {
            url: tourl
          },
          corpId: app.globalData.initdata.corpid
        })
        return
      }
      if (tourl == 'scan::') {
        if (app.globalData.platform == 'h5') {
          app.alert('请使用微信扫一扫功能扫码')
          return
        } else if (app.globalData.platform == 'mp') {
          var jweixin = require('jweixin-module')
          jweixin.ready(function () {
            //需在用户可能点击分享按钮前就先调用
            jweixin.scanQRCode({
              needResult: 0, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
              scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
              success: function (res) {
                var content = res.resultStr // 当needResult 为 1 时，扫码返回的结果
                //app.goto(content);
              }
            })
          })
        } else {
          uni.scanCode({
            success: function (res) {
              console.log(res)
              if (res.path) {
                app.goto('/' + res.path)
              } else {
                var content = res.result
                app.goto(content)
              }
            }
          })
        }
        return
      }
      if (tourl == 'share::') {
        if (app.globalData.platform == 'h5' || app.globalData.platform == 'mp') {
          app.error('点击右上角发送给好友或分享到朋友圈')
        }
        if (app.globalData.platform == 'app') {
          uni.showActionSheet({
            itemList: ['发送给微信好友', '分享到微信朋友圈'],
            success: function (res) {
              if (res.tapIndex >= 0) {
                var scene = 'WXSceneSession'
                if (res.tapIndex == 1) {
                  scene = 'WXSenceTimeline'
                }
                var sharedata = {}
                sharedata.provider = 'weixin'
                sharedata.type = 0
                sharedata.scene = scene
                sharedata.title = app.globalData.initdata.name
                var fullurl = app._fullurl()
                if (app.globalData.mid > 0) {
                  fullurl += (fullurl.indexOf('?') === -1 ? '?' : '&') + 'pid=' + app.globalData.mid
                }
                sharedata.href = app.globalData.pre_url + '/h5/' + app.globalData.aid + '.html#' + fullurl
                sharedata.imageUrl = app.globalData.initdata.logo
                sharedata.summary = app.globalData.initdata.desc

                var sharelist = app.globalData.initdata.sharelist
                if (sharelist) {
                  for (var i = 0; i < sharelist.length; i++) {
                    if (sharelist[i]['indexurl'] == app._fullurl()) {
                      sharedata.title = sharelist[i].title
                      sharedata.summary = sharelist[i].desc
                      sharedata.imageUrl = sharelist[i].pic
                      if (sharelist[i].url) {
                        var sharelink = sharelist[i].url
                        if (sharelink.indexOf('/') === 0) {
                          sharelink = app.globalData.pre_url + '/h5/' + app.globalData.aid + '.html#' + sharelink
                        }
                        if (app.globalData.mid > 0) {
                          sharelink += (sharelink.indexOf('?') === -1 ? '?' : '&') + 'pid=' + app.globalData.mid
                        }
                        sharedata.href = sharelink
                      }
                    }
                  }
                }
                uni.share(sharedata)
              }
            }
          })
        }
        return
      }
      if (!tourl || tourl == 'contact::' || tourl == 'share::') return
      if (tourl.indexOf('tel::') === 0) {
        //打电话
        tourl = tourl.slice(5)
        uni.makePhoneCall({
          phoneNumber: tourl
        })
        return
      }
      if (tourl.indexOf('tel:') === 0) {
        //打电话
        tourl = tourl.slice(4)
        uni.makePhoneCall({
          phoneNumber: tourl
        })
        return
      }
      if (tourl.indexOf('url::') === 0) {
        //外部链接
        if (app.globalData.platform == 'h5' || app.globalData.platform == 'mp') {
          location.href = tourl.slice(5)
        } else {
          tourl = '/pages/index/webView?url=' + encodeURIComponent(tourl.slice(5))
        }
      }
      if (tourl.indexOf('https://') === 0 || tourl.indexOf('http://') === 0) {
        //外部链接
        //判断外链参数
        tourl += (tourl.indexOf('?') > 0 ? '&' : '?') + 'dianda_aid=' + app.globalData.aid + '&dianda_mid=' + app.globalData.mid
        if (app.globalData.platform == 'h5' || app.globalData.platform == 'mp') {
          location.href = tourl
        } else {
          tourl = '/pages/index/webView?url=' + encodeURIComponent(tourl)
        }
      }
      if (tourl.indexOf('miniProgram::') === 0) {
        //其他小程序
        tourl = tourl.slice(13)
        var tourlArr = tourl.split('|') //console.log(tourlArr)
        if (app.globalData.platform == 'app') {
          plus.share.getServices(
            function (res) {
              var sweixin = null
              for (var i = 0; i < res.length; i++) {
                var t = res[i]
                if (t.id == 'weixin') {
                  sweixin = t
                }
              }
              if (sweixin) {
                sweixin.launchMiniProgram({
                  id: tourlArr[2],
                  type: 0,
                  path: tourlArr[1] ? tourlArr[1] : ''
                })
              }
            },
            function (res) {
              console.log(JSON.stringify(res))
            }
          )
        } else {
          uni.navigateToMiniProgram({
            appId: tourlArr[0],
            path: tourlArr[1] ? tourlArr[1] : '',
            complete: function () {
              if (tourlArr[2]) {
                app.goto(tourlArr[2])
              }
            }
          })
        }
        return
      }
      if (tourl == 'getmembercard::') {
        //领取会员卡
        app.post(
          'ApiCoupon/getmembercardparam',
          {
            card_id: ''
          },
          function (res) {
            if (res.status == 0) {
              app.alert(res.msg)
              return
            }
            if (app.globalData.platform == 'wx') {
              uni.navigateToMiniProgram({
                appId: 'wxeb490c6f9b154ef9',
                // 固定为此appid，不可改动
                extraData: res.extraData,
                // 包括encrypt_card_id outer_str biz三个字段，须从step3中获得的链接中获取参数
                success: function () {},
                fail: function () {},
                complete: function () {}
              })
            } else {
              location.href = res.ret_url
            }
          }
        )
        return
      }
      if (tourl.indexOf('location::') === 0) {
        //坐标导航
        tourl = tourl.slice(10)
        var tourlArr = tourl.split('|')
        var jwd = tourlArr[1].split(',')
        uni.openLocation({
          latitude: parseFloat(jwd[1]),
          longitude: parseFloat(jwd[0]),
          name: tourlArr[0],
          scale: 13
        })
        return
      }
      if (tourl.indexOf('plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin') === 0) {
        //小程序直播 带参数
        tourl =
          tourl +
          '&custom_params=' +
          encodeURIComponent(
            JSON.stringify({
              pid: app.globalData.mid
            })
          )
      }
      if (tourl.indexOf('copy::') === 0) {
        //复制
        tourl = tourl.slice(6)
        var tourlArr = tourl.split('|')
        uni.setClipboardData({
          data: tourlArr[0],
          showToast: false,
          success: function () {
            if (tourlArr[1] != '复制成功') app.alert(tourlArr[1])
            else if (tourlArr[1]) app.error(tourlArr[1])
          }
        })
        return
      }
      if (tourl.indexOf('rewardedVideoAd::') === 0) {
        console.log('rewardedVideoAd')
        tourl = tourl.slice(17)
        var tourlArr = tourl.split('|')
        if (wx.createRewardedVideoAd) {
          app.showLoading()
          app.post('ApiRewardVideoAd/getunitid', { hid: tourlArr[0] }, function (postres) {
            //app.showLoading(false);
            if (postres.status == 0) {
              app.alert(postres.msg)
              return
            }
            if (!app.globalData.rewardedVideoAd[postres.unitid]) {
              app.globalData.rewardedVideoAd[postres.unitid] = wx.createRewardedVideoAd({ adUnitId: postres.unitid })
            }
            var rewardedVideoAd = app.globalData.rewardedVideoAd[postres.unitid]
            rewardedVideoAd
              .load()
              .then(() => {
                app.showLoading(false)
                rewardedVideoAd.show()
              })
              .catch(err => {
                app.alert('加载失败')
              })
            rewardedVideoAd.onError(err => {
              app.showLoading(false)
              app.alert(err)
              console.log('onError event emit', err)
              rewardedVideoAd.offLoad()
              rewardedVideoAd.offClose()
            })
            rewardedVideoAd.onClose(res => {
              if (res && res.isEnded) {
                //app.alert('播放结束 发放奖励');
                app.post('ApiRewardVideoAd/givereward', { hid: tourlArr[0] }, function (res3) {
                  if (res3.status == 0) {
                    app.alert(res3.msg)
                  } else {
                    app.success(res3.msg)
                  }
                })
              } else {
                console.log('播放中途退出，不下发奖励')
              }
              rewardedVideoAd.offLoad()
              rewardedVideoAd.offClose()
            })
          })
        }
        return false
      }

      if (app.isNull(opentype)) {
        var mv = tourl.split('?')
        var urlpath = mv[0]
        if (app.globalData.platform == 'h5' && urlpath == app._fullurl()) {
          opentype = 'reLaunch'
        } else {
          opentype = 'navigate'
        }
      }
      app.globalData.rewardedVideoAd = {}
      if (opentype == 'switchTab') {
        var args = new Object()
        var name, value
        var url = tourl //跳转链接
        var num = url.indexOf('?')
        if (num >= 0) {
          var urlbase = url.substr(0, num)
          var str = url.substr(num + 1) //取得所有参数

          var arr = str.split('&') //各个参数放到数组里

          for (var i = 0; i < arr.length; i++) {
            num = arr[i].indexOf('=')

            if (num > 0) {
              name = arr[i].substring(0, num)
              value = arr[i].substr(num + 1)
              args[name] = value
            }
          }
          uni.switchTab({
            url: urlbase,
            success: function (e) {
              var page = getCurrentPages().pop()
              if (page == undefined || page == null) return
              page.onLoad(args)
            }
          })
        } else {
          uni.switchTab({
            url: tourl
          })
        }
      } else if (opentype == 'redirect' || opentype == 'redirectTo') {
        uni.redirectTo({
          url: tourl
        })
      } else if (opentype == 'reLaunch') {
        uni.reLaunch({
          url: tourl
        })
      } else {
        var pages = getCurrentPages()

        if (pages.length >= 10) {
          uni.redirectTo({
            url: tourl
          })
        } else {
          uni.navigateTo({
            url: tourl
          })
        }
      }
    },
    goback: function (isreload) {
      var app = this
      var pages = getCurrentPages()
      if (isreload && pages.length > 1) {
        var prePage = pages[pages.length - 2]
        prePage.$vm.getdata()
      }
      if (pages.length == 1) {
        app.goto(app.globalData.indexurl, 'reLaunch')
      } else {
        uni.navigateBack({
          fail: function () {
            app.goto(app.globalData.indexurl, 'reLaunch')
          }
        })
      }
    },
    post: function (url, param, callback) {
      this.request('POST', url, param, callback)
    },
    get: function (url, param, callback) {
      this.request('GET', url, param, callback)
    },
    request: function (method, url, param, callback) {
      var oldurl = url
      var app = this
      if (url.substring(0, 8) != 'https://') {
        url = app.globalData.baseurl + url
        url += (url.indexOf('?') > 0 ? '&' : '?') + 'aid=' + app.globalData.aid + '&platform=' + app.globalData.platform + '&session_id=' + app.globalData.session_id + '&pid=' + app.globalData.pid
        if (app.globalData.isdouyin == 1) {
          url += '&isdouyin=1'
        }
        if (!app.globalData.isinit) {
          url += '&needinit=1'
          if (app.globalData.uid) url += '&uid=' + app.globalData.uid
        }
      }
      uni.request({
        url: url,
        //仅为示例，并非真实的接口地址
        data: param,
        method: method,
        success: function (res) {
          app.setinitdata(res)
          if (res.data && res.data.status == -1) {
            //跳转登录页
            app.showLoading(false)
            if (app.globalData.initdata.logintype.length == 0 && app.inArray(app.globalData.platform, ['wx', 'mp', 'baidu', 'qq', 'toutiao', 'alipay'])) return
            var pages = getCurrentPages()
            var currentPage = pages[pages.length - 1]
            currentPage.$vm.loading = false
            var frompage = ''
            var nowurl = app._url()
            var opentype = 'reLaunch'
            if (app.globalData.platform == 'baidu') {
              if (nowurl == '/pages/my/usercenter') {
                opentype = 'redirect'
              } else {
                opentype = 'navigate'
              }
            }
            if (nowurl != '/pages/index/login' && nowurl != '/pages/index/reg' && nowurl != '/pages/index/getpwd') {
              var frompage = encodeURIComponent(app._fullurl())
            }
            if (res.data.authlogin == 1) {
              app.authlogin(function (res2) {
                if (res2.status == 1) {
                  if (res2.msg) app.success(res2.msg)
                  currentPage.$vm.getdata()
                } else if (res2.status == 2) {
                  app.goto('/pages/index/login?frompage=' + frompage + '&logintype=4&login_bind=1', opentype)
                } else {
                  console.log(res2)
                  app.goto('/pages/index/login?frompage=' + frompage, opentype)
                }
              })
            } else {
              app.goto('/pages/index/login?frompage=' + frompage, opentype)
              return
            }
          } else if (res.data && res.data.status == -10) {
            //跳转管理员登录
            app.showLoading(false)
            var pages = getCurrentPages()
            var currentPage = pages[pages.length - 1]
            currentPage.$vm.loading = false
            //管理员登录
            app.goto('/admin/index/login', 'redirect')
          } else if (res.data && res.data.status == -2) {
            //公众号或h5跳转
            app.showLoading(false)
            var pages = getCurrentPages()
            var currentPage = pages[pages.length - 1]
            currentPage.$vm.loading = false
            //跳转
            location.href = res.data.url
          } else if (res.data && res.data.status == -3) {
            //跳转到指定页
            app.showLoading(false)
            var pages = getCurrentPages()
            var currentPage = pages[pages.length - 1]
            currentPage.$vm.loading = false
            //跳转
            app.goto(res.data.url, 'redirect')
          } else if (res.data && res.data.status == -4) {
            //弹窗提示并跳转到指定页
            app.showLoading(false)
            var pages = getCurrentPages()
            var currentPage = pages[pages.length - 1]
            currentPage.$vm.loading = false
            //弹出提示
            app.alert(res.data.msg, function () {
              if (res.data.url) {
                app.goto(res.data.url, 'redirect')
              }
            })
          } else {
            typeof callback == 'function' && callback(res.data)
          }
        },
        fail: function (res) {
          try {
            if (oldurl != 'ApiIndex/linked') {
              if (res.errMsg != 'request:fail timeout') {
                console.log(res)
                //app.alert('请求失败：' + JSON.stringify(res));
              }
            }
          } catch (e) {}
        }
      })
    },
    baselogin: function (callback) {
      console.log('baselogin')
      var app = this
      if (app.globalData.platform == 'wx') {
        wx.login({
          success(res1) {
            var code = res1.code
            app.post(
              'ApiIndex/wxbaselogin',
              {
                code: code,
                pid: app.globalData.pid
              },
              function (res) {
                typeof callback == 'function' && callback(res)
              }
            )
          }
        })
      } else if (app.globalData.platform == 'baidu') {
        swan.getLoginCode({
          success(res1) {
            console.log(res1)
            var code = res1.code
            app.post(
              'ApiIndex/baidulogin',
              {
                code: code,
                pid: app.globalData.pid
              },
              function (res) {
                typeof callback == 'function' && callback(res)
              }
            )
          },
          fail(res2) {
            console.log(res2)
          }
        })
      } else if (app.globalData.platform == 'qq') {
        qq.login({
          success(res1) {
            app.post(
              'ApiIndex/qqlogin',
              {
                code: res1.code,
                pid: app.globalData.pid
              },
              function (res) {
                typeof callback == 'function' && callback(res)
              }
            )
          }
        })
      } else if (app.globalData.platform == 'toutiao') {
        tt.login({
          force: true,
          success(res1) {
            app.post(
              'ApiIndex/toutiaologin',
              {
                code: res1.code,
                pid: app.globalData.pid
              },
              function (res) {
                typeof callback == 'function' && callback(res)
              }
            )
          }
        })
      } else if (app.globalData.platform == 'alipay') {
        my.getAuthCode({
          scopes: 'auth_base',
          success(res1) {
            app.post(
              'ApiIndex/alipaylogin',
              {
                code: res1.authCode,
                pid: app.globalData.pid
              },
              function (res) {
                typeof callback == 'function' && callback(res)
              }
            )
          }
        })
      } else if (app.globalData.platform == 'mp') {
        var frompage = ''
        var nowurl = app._url()
        if (nowurl != '/pages/index/login' && nowurl != '/pages/index/reg' && nowurl != '/pages/index/getpwd') {
          frompage = encodeURIComponent(app._fullurl())
        }
        location.href =
          app.globalData.pre_url +
          '/index.php?s=ApiIndex/mpbaselogin&aid=' +
          app.globalData.aid +
          '&session_id=' +
          app.globalData.session_id +
          '&pid=' +
          app.globalData.pid +
          '&frompage=' +
          encodeURIComponent(frompage)
      }
    },
    authlogin: function (callback, params) {
      var app = this
      if (app.globalData.platform == 'wx') {
        wx.getUserProfile({
          lang: 'zh_CN',
          desc: '用于展示头像昵称',
          success: function (res2) {
            console.log(res2)
            var userinfo = res2.userInfo
            wx.login({
              success(res1) {
                var code = res1.code
                app.post(
                  'ApiIndex/wxlogin',
                  {
                    code: code,
                    userinfo: userinfo,
                    pid: app.globalData.pid
                  },
                  function (res) {
                    typeof callback == 'function' && callback(res)
                  }
                )
              }
            })
          },
          fail: function (res2) {
            console.log(res2)
            if (res2.errMsg == 'getUserProfile:fail auth deny') {
            } else {
              typeof callback == 'function' &&
                callback({
                  status: 0,
                  msg: res2.errMsg
                })
            }
          }
        })
      } else if (app.globalData.platform == 'mp' || app.globalData.platform == 'h5') {
        var frompage = ''
        var nowurl = app._url()
        if (nowurl != '/pages/index/login' && nowurl != '/pages/index/reg' && nowurl != '/pages/index/getpwd') {
          frompage = encodeURIComponent(app._fullurl())
        }
        if (params && params.frompage) {
          frompage = params.frompage
        }
        location.href =
          app.globalData.pre_url +
          '/index.php?s=ApiIndex/shouquan&aid=' +
          app.globalData.aid +
          '&session_id=' +
          app.globalData.session_id +
          '&pid=' +
          app.globalData.pid +
          '&frompage=' +
          encodeURIComponent(frompage)
      } else if (app.globalData.platform == 'app') {
        plus.oauth.getServices(function (services) {
          console.log(services)
          let s = services[0]
          for (var i in services) {
            var service = services[i]
            if (service.id == 'weixin') {
              s = service
            }
          }
          console.log(s)
          console.log('x----')
          s.authorize(function (e) {
            console.log(e)
            var code = e.code
            app.post(
              'ApiIndex/appwxlogin',
              {
                code: code,
                pid: app.globalData.pid
              },
              function (res) {
                typeof callback == 'function' && callback(res)
              }
            )
          })
        })
      } else if (app.globalData.platform == 'baidu') {
        swan.getLoginCode({
          success: res => {
            console.log('getLoginCode success', res)
            var code = res.code
            app.post(
              'ApiIndex/baidulogin',
              {
                code: code,
                pid: app.globalData.pid
              },
              function (res) {
                typeof callback == 'function' && callback(res)
              }
            )
          },
          fail: err => {
            typeof callback == 'function' &&
              callback({
                status: 0,
                msg: err.errMsg
              })
          }
        })
      } else if (app.globalData.platform == 'qq') {
        qq.login({
          success(res) {
            if (res.code) {
              app.post(
                'ApiIndex/qqlogin',
                {
                  code: res.code,
                  pid: app.globalData.pid
                },
                function (res) {
                  typeof callback == 'function' && callback(res)
                }
              )
            } else {
              typeof callback == 'function' &&
                callback({
                  status: 0,
                  msg: res.errMsg
                })
            }
          },
          fail(res) {
            typeof callback == 'function' &&
              callback({
                status: 0,
                msg: res.errMsg
              })
          }
        })
      } else if (app.globalData.platform == 'toutiao') {
        tt.login({
          force: true,
          success(res) {
            if (res.code) {
              app.post(
                'ApiIndex/toutiaologin',
                {
                  code: res.code,
                  pid: app.globalData.pid
                },
                function (res) {
                  typeof callback == 'function' && callback(res)
                }
              )
            } else {
              typeof callback == 'function' &&
                callback({
                  status: 0,
                  msg: res.errMsg
                })
            }
          },
          fail(res) {
            typeof callback == 'function' &&
              callback({
                status: 0,
                msg: res.errMsg
              })
          }
        })
      } else if (app.globalData.platform == 'alipay') {
        my.getAuthCode({
          scopes: 'auth_base',
          success: res => {
            console.log(res)
            if (res.authCode) {
              app.post(
                'ApiIndex/alipaylogin',
                {
                  code: res.authCode,
                  pid: app.globalData.pid
                },
                function (res) {
                  typeof callback == 'function' && callback(res)
                }
              )
            }
          },
          fail: res => {
            typeof callback == 'function' &&
              callback({
                status: 0,
                msg: res.errMsg
              })
          }
        })
      }
    },
    setinitdata: function (res) {
      var app = this
      var oldmid = app.globalData.mid
      if (res && res.data && (res.data.mid || res.data.mid === 0) && app.globalData.mid != res.data.mid) {
        app.globalData.mid = res.data.mid
        if (res.data.session_id) {
          uni.setStorageSync('session_id', res.data.session_id)
          app.globalData.session_id = res.data.session_id
        }
        if (res.data.gtktoken) {
          uni.setStorageSync('gtktoken', res.data.gtktoken)
          app.globalData.gtktoken = res.data.gtktoken
        }
        if (app.globalData.mid) {
          app.globalData.socket_token = res.data.socket_token
          app.openSocket()
          uni.removeStorageSync('pid')
        }
      }
      if (res && res.data && res.data._initdata) {
        app.globalData.isinit = true
        res.data._initdata.pre_url = app.globalData.pre_url
        app.globalData.initdata = res.data._initdata
        app.globalData.mid = res.data._initdata.mid
        app.globalData.isdouyin = res.data._initdata.isdouyin
        uni.setStorageSync('session_id', res.data._initdata.session_id)
        app.globalData.session_id = res.data._initdata.session_id
        if (app.globalData.platform == 'mp') {
          var share_package = res.data.share_package
          var jweixin = require('jweixin-module')
          jweixin.config({
            debug: false,
            appId: share_package.appId,
            timestamp: share_package.timestamp,
            nonceStr: share_package.nonceStr,
            signature: share_package.signature,
            jsApiList: [
              'checkJsApi',
              'onMenuShareAppMessage',
              'onMenuShareTimeline',
              'updateAppMessageShareData',
              'updateTimelineShareData',
              'chooseImage',
              'previewImage',
              'uploadImage',
              'openLocation',
              'getLocation',
              'closeWindow',
              'scanQRCode',
              'chooseWXPay',
              'addCard',
              'chooseCard',
              'openCard'
            ],
            openTagList: ['wx-open-launch-weapp']
          })
        }
        if (app.globalData.mid) {
          app.globalData.socket_token = res.data.socket_token
          app.openSocket()
          uni.removeStorageSync('pid')
        }
        if (!app.globalData.mid && app.globalData.initdata.logintype.length == 0) {
          app.baselogin(function (res2) {
            var pages = getCurrentPages() //获取加载的页面
            var currentPage = pages[pages.length - 1] //获取当前页面的对象
            var url = '/' + (currentPage.route ? currentPage.route : currentPage.__route__) //当前页面url
            if (url == '/pages/index/login') {
              if (app.globalData.platform == 'baidu') {
                var opts = currentPage.options
              } else {
                var opts = currentPage.$vm.opt
              }
              console.log(opts)
              if (opts && opts.frompage) {
                app.goto(decodeURIComponent(opts.frompage), 'redirect')
              } else {
                app.goto('/pages/my/usercenter', 'redirect')
              }
            } else {
              currentPage.$vm.getdata()
            }
          })
        }
      }
      if (app.globalData.mid && app.globalData.mid != oldmid) {
        if (app.globalData.platform == 'wx') {
          wx.login({
            success: function (res) {
              if (res.code) {
                app.post(
                  'ApiIndex/setwxopenid',
                  {
                    code: res.code
                  },
                  function () {}
                )
              }
            }
          })
        } else if (app.globalData.platform == 'alipay') {
          my.getAuthCode({
            scopes: ['auth_base'],
            success: res => {
              if (res.authCode) {
                app.post(
                  'ApiIndex/setalipayopenid',
                  {
                    code: res.authCode
                  },
                  function () {}
                )
              }
            }
          })
        } else if (app.globalData.platform == 'baidu') {
          swan.getLoginCode({
            success: res => {
              if (res.code) {
                app.post(
                  'ApiIndex/setbaiduopenid',
                  {
                    code: res.code
                  },
                  function () {}
                )
              }
            },
            fail: err => {
              console.log('getLoginCode fail', err)
            }
          })
        }
      }
    },
    //启用socket连接
    openSocket: function () {
      console.log('openSocket')
      //#ifndef MP-TOUTIAO
      var app = this
      app.globalData.socketOpen = false
      uni.closeSocket()

      uni.connectSocket({
        url: app.globalData.pre_url.replace('https://', 'wss://') + '/wss'
      })
      app.sendSocketMessage({
        type: 'khinit',
        data: {
          aid: app.globalData.aid,
          mid: app.globalData.mid,
          platform: app.globalData.platform
        }
      })
      clearInterval(app.globalData.socketInterval)
      app.globalData.socketInterval = setInterval(function () {
        app.sendSocketMessage({
          type: 'connect'
        })
      }, 25000)
      //#endif
    },
    sendSocketMessage: function (msg) {
      var app = this
      if (!msg.token) msg.token = this.globalData.socket_token
      if (app.globalData.socketOpen) {
        console.log(msg)
        uni.sendSocketMessage({
          data: JSON.stringify(msg),
          fail: function (res) {
            console.log(res)
            console.log('发送失败')
            if (app.globalData.socketConnecttimes < 1) {
              app.globalData.socketConnecttimes++
              app.globalData.socketMsgQueue.push(msg)
              console.log('openSocket 重连')
              // 智哥注意
              uni.closeSocket()
              // app.openSocket()
            }
          },
          success: function () {
            console.log('发送成功')
            app.globalData.socketConnecttimes = 0
          }
        })
      } else {
        this.globalData.socketMsgQueue.push(msg)
      }
    },
    chooseImage: function (callback, count, ossSign) {
      var app = this
      uni.chooseImage({
        count: count || 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success: function (res) {
          let tempFilePaths = res.tempFilePaths
          let tempFiles = res.tempFiles
          let imageUrls = []
          for (let i = 0; i < tempFilePaths.length; i++) {
            app.showLoading('上传中')
            let randomName = new Date().getTime() + Math.round(Math.random() * 100) + '.png'
            uni.uploadFile({
              url: ossSign.host,
              filePath: tempFilePaths[i],
              formData: {
                key: ossSign.dir + randomName,
                OSSAccessKeyId: ossSign.accessid,
                policy: ossSign.policy,
                Signature: ossSign.signature,
                callback: ossSign.callback,
                success_action_status: 200
              },
              name: 'file',
              success: function (res) {
                app.showLoading(false)
                // 地址+文件夹+文件名
                let str = ossSign.host + ossSign.dir + randomName
                imageUrls.push(str)
                if (imageUrls.length == tempFilePaths.length) {
                  typeof callback == 'function' && callback(imageUrls)
                }
              },
              fail: function (res) {
                app.showLoading(false)
                app.alert(res.errMsg)
              }
            })
          }
        },
        fail: function (res) {
          //alert(res.errMsg);
        }
      })
    },
    getLocation: function (callback1, callback2) {
      var that = this
      if (this.globalData.platform == 'mp') {
        var jweixin = require('jweixin-module')
        jweixin.ready(function () {
          jweixin.getLocation({
            type: 'gcj02',
            success: function (res) {
              that.setCache('getLocationCatch', res)
              typeof callback1 == 'function' && callback1(res)
            },
            fail: function (res) {
              var locationCatch = that.getCache('getLocationCatch')
              if (locationCatch) {
                typeof callback1 == 'function' && callback1(locationCatch)
              } else {
                typeof callback2 == 'function' && callback2(res)
              }
            }
          })
        })
      } else if (this.globalData.platform == 'alipay') {
        uni.getLocation({
          success: function (res) {
            that.setCache('getLocationCatch', res)
            typeof callback1 == 'function' && callback1(res)
          },
          fail: function (res) {
            var locationCatch = that.getCache('getLocationCatch')
            if (locationCatch) {
              typeof callback1 == 'function' && callback1(locationCatch)
            } else {
              typeof callback2 == 'function' && callback2(res)
            }
          }
        })
      } else {
        uni.getLocation({
          type: 'gcj02',
          success: function (res) {
            that.setCache('getLocationCatch', res)
            typeof callback1 == 'function' && callback1(res)
          },
          fail: function (res) {
            var locationCatch = that.getCache('getLocationCatch')
            if (locationCatch) {
              typeof callback1 == 'function' && callback1(locationCatch)
            } else {
              typeof callback2 == 'function' && callback2(res)
            }
          }
        })
      }
    },
    setCache: function (key, value) {
      return uni.setStorageSync(key, value)
    },
    getCache: function (key) {
      return uni.getStorageSync(key)
    },
    removeCache: function (key) {
      var $ = this
      if ($.isNull(key)) {
        uni.clearStorageSync()
      } else {
        uni.removeStorageSync(key)
      }
    },
    _url: function () {
      //获取当前页url
      var pages = getCurrentPages() //获取加载的页面
      var currentPage = pages[pages.length - 1] //获取当前页面的对象
      var url = '/' + (currentPage.route ? currentPage.route : currentPage.__route__) //当前页面url
      return url
    },
    _fullurl: function () {
      var pages = getCurrentPages() //获取加载的页面
      var currentPage = pages[pages.length - 1] //获取当前页面的对象
      var url = '/' + (currentPage.route ? currentPage.route : currentPage.__route__) //当前页面url
      if (this.globalData.platform == 'baidu') {
        var opts = currentPage.options
      } else {
        var opts = currentPage.$vm.opt
      }
      console.log(opts)
      var params = []
      for (var i in opts) {
        params.push(i + '=' + opts[i])
      }
      if (params.length > 0) {
        url += '?' + params.join('&')
      }
      console.log(url)
      return url
    },
    checkUpdateVersion() {
      if (wx.canIUse('getUpdateManager')) {
        //创建 UpdateManager 实例
        const updateManager = wx.getUpdateManager()
        //console.log('是否进入模拟更新');
        //检测版本更新
        updateManager.onCheckForUpdate(function (res) {
          //console.log('是否获取版本');
          // 请求完新版本信息的回调
          if (res.hasUpdate) {
            //监听小程序有版本更新事件
            updateManager.onUpdateReady(function () {
              //TODO 新的版本已经下载好，调用 applyUpdate 应用新版本并重启 （ 此处进行了自动更新操作）
              updateManager.applyUpdate()
            })
            updateManager.onUpdateFailed(function () {
              // 新版本下载失败
              //wx.showModal({
              //	title: '已经有新版本喽~',
              //	content: '请您删除当前小程序，到微信 “发现-小程序” 页，重新搜索打开哦~',
              //})
            })
          }
        })
      } else {
        //TODO 此时微信版本太低（一般而言版本都是支持的）
        //wx.showModal({
        //  title: '溫馨提示',
        //  content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
        //})
      }
    },
    checkArguments() {
      if (plus.runtime.launcher == 'miniProgram') {
        let result = plus.runtime.arguments
        console.log('wxpay result: ' + result)
        //...
      }
    }
  }
}
</script>
<style lang="scss">
@import '/static/css/uni.scss';

/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
@import 'uview-ui/index.scss';

@import './common.css';
@import './iconfont.css';
@import '@/components/parse/parse.css';
</style>
